package com.nsgf.library.ui.page;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.Observer;

import com.google.android.material.bottomsheet.BottomSheetBehavior;

import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WeatherBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityPatrolReviewBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.matisse.MimeType;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.photopicker.widget.PhotoAdapter;
import com.nsgf.library.ui.adapter.WeatherListAdapter;
import com.nsgf.library.ui.adapter.StructureComponentAdapter;
import com.nsgf.library.data.bean.StructureComponentBean;
import com.nsgf.skjz.utils.ToastUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.nsgf.library.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

/**
 * 审核巡查页面
 */
public class PatrolReviewActivity extends BaseActivity {

    PatrolReviewStates states;
    private ActivityPatrolReviewBinding mBinding;
    private AccountRequester mAccountRequester;

    private int selectedWeatherIndex = 0; // 0-晴 1-阴 2-雨 3-雪
    private List<WeatherBean.DataBean> weatherList = new ArrayList<>(); // 天气列表数据
    private int checkResult = 0; // 0-正常 1-异常

    private WeatherListAdapter mAdapter;
    private StructureComponentAdapter mStructureComponentAdapter;
    private List<StructureComponentBean> structureComponentList = new ArrayList<>(); // 结构组件列表
    private List<WorkOrderDetailBean.FileDto> selectedVideos = new ArrayList<>(); // 已选择的视频列表
    private List<WorkOrderDetailBean.FileDto> selectedVideosHandling = new ArrayList<>(); // 处理情况已选择的视频列表
    private static final int REQUEST_CODE_VIDEO = 1001; // 视频选择请求码
    private static final int REQUEST_CODE_VIDEO_HANDLING = 1002; // 处理情况视频选择请求码
    private static final int REQUEST_CODE_IMAGE_HANDLING = 1003; // 处理情况图片选择请求码
    private BottomSheetBehavior<NestedScrollView> mBottomSheetBehavior; // 底部抽屉行为

    @Override
    protected void initViewModel() {
        states = getActivityScopeViewModel(PatrolReviewStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new WeatherListAdapter(this);
        mStructureComponentAdapter = new StructureComponentAdapter(this);
        return new DataBindingConfig(R.layout.activity_patrol_review, BR.vm, states)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityPatrolReviewBinding) getBinding();

        // 初始化标题栏
        initTitleBar();

        // 初始化WebView地图
        initWebView();

        // 初始化数据
        initData();

        // 初始化观察者
        initObserver();

        // 加载天气数据
        loadWeatherData();

        // 初始化图片选择器
        initImagePicker();
        
        // 初始化处理情况图片选择器
        initImagePickerHandling();

        // 初始化底部抽屉
        initBottomSheet();
        
        // 初始化处理时间
        initHandlingTime();
    }

    /**
     * 初始化处理时间
     */
    private void initHandlingTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        states.handlingTime.set(sdf.format(new Date()));
        
        // 设置默认处理人
        String userName = UserInfo.getInstance().getName();
        if (userName != null && !userName.isEmpty()) {
            states.handler.set(userName);
        }
    }

    /**
     * 初始化底部抽屉
     */
    private void initBottomSheet() {
        mBottomSheetBehavior = BottomSheetBehavior.from(mBinding.bottomSheet);
        // 设置默认状态为收起（显示peekHeight）
        mBottomSheetBehavior.setState(STATE_COLLAPSED);
        
        // 设置可以拖拽隐藏
        mBottomSheetBehavior.setHideable(true);
        
        // 添加状态回调
        mBottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                // 如果完全隐藏，则恢复到收起状态
                if (newState == STATE_HIDDEN) {
                    mBottomSheetBehavior.setState(STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                // 滑动过程中的回调，可以用于实现动画效果
            }
        });
    }

    /**
     * 初始化标题栏
     */
    private void initTitleBar() {
        mBinding.titlebar.titleBarBack.setOnClickListener(v -> finish());
    }

    /**
     * 初始化WebView地图
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings webSettings = mBinding.webView.getWebView().getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        // 设置WebViewClient
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient());

        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 从Intent获取传递的巡查数据（如果有）
        // TODO: 从Intent或API获取巡查数据并填充到界面
        
        // 设置默认巡查时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        states.patrolTime.set(sdf.format(new Date()));

        // 获取传递的巡查对象（从选择页面传递过来）
        String patrolObject = null;
        if (getIntent() != null) {
            patrolObject = getIntent().getStringExtra("patrolObject");
        }
        
        // 如果Intent中有传递，使用传递的值，否则从UserInfo获取
        if (patrolObject != null && !patrolObject.isEmpty()) {
            states.patrolObject.set(patrolObject);
        } else {
            String projectName = UserInfo.getInstance().getProjectName();
            if (projectName != null && !projectName.isEmpty()) {
                states.patrolObject.set(projectName);
            }
        }

        // 设置默认巡查人员（可以从UserInfo获取）
        String userName = UserInfo.getInstance().getName();
        if (userName != null && !userName.isEmpty()) {
            states.patrolPerson.set(userName);
        }

        // 初始化天气UI
        updateWeatherUI();

        // 初始化检查结果UI
        updateCheckResultUI();
        
        // 初始化异常情况显示状态
        updateAbnormalSituationVisibility();
        
        // 初始化结构组件列表
        initStructureComponents();

        mAdapter.setOnItemClickListener((viewId, item, position) -> {
            for (int i = 0; i < mAdapter.getCurrentList().size(); i++) {
                mAdapter.getCurrentList().get(i).setSelectWeather(false);
            }
            mAdapter.getCurrentList().get(position).setSelectWeather(true);
            mAdapter.notifyDataSetChanged();
        });

    }

    /**
     * 初始化观察者
     */
    private void initObserver() {
        getLifecycle().addObserver(mAccountRequester);
    }

    /**
     * 加载天气数据
     */
    private void loadWeatherData() {
        mAccountRequester.getDictItems("weather.type");
    }

    /**
     * 初始化结构组件列表
     */
    private void initStructureComponents() {
        structureComponentList.clear();
        structureComponentList.add(new StructureComponentBean("闸墩"));
        structureComponentList.add(new StructureComponentBean("边墙"));
        structureComponentList.add(new StructureComponentBean("胸墙"));
        structureComponentList.add(new StructureComponentBean("工作桥"));
        
        mStructureComponentAdapter.submitList(structureComponentList);
        states.structureComponentAdapter.set(mStructureComponentAdapter);
    }
    
    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        mBinding.multiPickResultView.init(
                this,
                MultiPickResultView.ACTION_SELECT,  // 用于图片选择
                new ArrayList<WorkOrderDetailBean.FileDto>(),  // 初始图片列表（空）
                9,  // 最大选择数量
                0,  // index
                mimeTypes,
                new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {

                    }
                }
        );
    }
    
    /**
     * 初始化处理情况图片选择器
     */
    private void initImagePickerHandling() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        mBinding.multiPickResultViewHandling.init(
                this,
                MultiPickResultView.ACTION_SELECT,  // 用于图片选择
                new ArrayList<WorkOrderDetailBean.FileDto>(),  // 初始图片列表（空）
                9,  // 最大选择数量
                1,  // index
                mimeTypes,
                new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {

                    }
                }
        );
    }

    /**
     * 打开视频选择器
     */
    private void openVideoPicker() {
        Set<MimeType> mimeTypes = MimeType.ofVideo();

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(false)  // 不允许直接录制视频
                .maxSelectable(1)  // 最多选择1个视频
                .theme(R.style.Matisse_Dracula)  // 暗色主题
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(REQUEST_CODE_VIDEO);
    }

    /**
     * 打开处理情况视频选择器（支持多个）
     */
    private void openVideoPickerHandling() {
        Set<MimeType> mimeTypes = MimeType.ofVideo();

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(false)  // 不允许直接录制视频
                .maxSelectable(9)  // 最多选择9个视频
                .theme(R.style.Matisse_Dracula)  // 暗色主题
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(REQUEST_CODE_VIDEO_HANDLING);
    }

    /**
     * 更新视频显示
     */
    private void updateVideoDisplay() {
        LinearLayout videoListLayout = mBinding.llVideoList;
        videoListLayout.removeAllViews();
        
        if (selectedVideos != null && !selectedVideos.isEmpty()) {
            states.hasVideo.set(true);
            
            for (int i = 0; i < selectedVideos.size(); i++) {
                WorkOrderDetailBean.FileDto video = selectedVideos.get(i);
                
                // 创建视频预览视图
                LinearLayout videoItem = createVideoItem(video, i, selectedVideos);
                videoListLayout.addView(videoItem);
            }
        } else {
            states.hasVideo.set(false);
        }
    }
    
    /**
     * 更新处理情况视频显示
     */
    private void updateVideoDisplayHandling() {
        LinearLayout videoListLayout = mBinding.llVideoListHandling;
        videoListLayout.removeAllViews();
        
        if (selectedVideosHandling != null && !selectedVideosHandling.isEmpty()) {
            states.hasVideoHandling.set(true);
            
            for (int i = 0; i < selectedVideosHandling.size(); i++) {
                WorkOrderDetailBean.FileDto video = selectedVideosHandling.get(i);
                
                // 创建视频预览视图
                LinearLayout videoItem = createVideoItem(video, i, selectedVideosHandling);
                videoListLayout.addView(videoItem);
            }
        } else {
            states.hasVideoHandling.set(false);
        }
    }
    
    /**
     * 创建视频项视图
     */
    private LinearLayout createVideoItem(WorkOrderDetailBean.FileDto video, int index, List<WorkOrderDetailBean.FileDto> videoList) {
        // 创建视频预览视图
        LinearLayout videoItem = new LinearLayout(this);
        videoItem.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 0, 10, 0);
        videoItem.setLayoutParams(params);
        
        // 视频缩略图（可以使用ImageView显示第一帧）
        android.widget.ImageView thumbnail = new android.widget.ImageView(this);
        thumbnail.setLayoutParams(new LinearLayout.LayoutParams(80, 80));
        thumbnail.setScaleType(android.widget.ImageView.ScaleType.CENTER_CROP);
        thumbnail.setBackgroundResource(R.drawable.bg_upload_button);
        // 这里可以加载视频第一帧作为缩略图，暂时使用占位图
        
        // 删除按钮
        android.widget.ImageView deleteBtn = new android.widget.ImageView(this);
        LinearLayout.LayoutParams deleteParams = new LinearLayout.LayoutParams(20, 20);
        deleteParams.setMargins(70, -20, 0, 0);
        deleteBtn.setLayoutParams(deleteParams);
        deleteBtn.setBackgroundResource(R.drawable.ic_add); // 临时使用，实际应该使用删除图标
        deleteBtn.setRotation(45); // 旋转45度变成X
        final int videoIndex = index;
        deleteBtn.setOnClickListener(v -> {
            videoList.remove(videoIndex);
            if (videoList == selectedVideos) {
                if (selectedVideos.isEmpty()) {
                    states.hasVideo.set(false);
                }
                updateVideoDisplay();
            } else if (videoList == selectedVideosHandling) {
                if (selectedVideosHandling.isEmpty()) {
                    states.hasVideoHandling.set(false);
                }
                updateVideoDisplayHandling();
            }
        });
        
        videoItem.addView(thumbnail);
        videoItem.addView(deleteBtn);
        return videoItem;
    }

    /**
     * 打开图片选择器
     */
    private void openImagePicker() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        // 获取已选中的图片路径
        ArrayList<WorkOrderDetailBean.FileDto> selectedPaths = new ArrayList<>();
        if (mBinding.multiPickResultView.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultView.getPhotos()) {
                if (photo != null && photo.getFilePath() != null && !photo.getFilePath().startsWith("http")) {
                    selectedPaths.add(photo);
                }
            }
        }

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(true)  // 允许拍照
                .setSelectedImages(selectedPaths)  // 设置已选中的图片（SelectionCreator 会处理 null 情况）
                .captureStrategy(
                        new com.nsgf.library.matisse.internal.entity.CaptureStrategy(true, "com.nsgf.daye.fileprovider", "test"))
                .maxSelectable(9)  // 最大选择9张
                .theme(R.style.Matisse_Dracula)  // 暗色主题
                .originalEnable(true)  // 显示原图选项
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(PhotoPicker.REQUEST_CODE);
    }
    
    /**
     * 打开处理情况图片选择器
     */
    private void openImagePickerHandling() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        // 获取已选中的图片路径
        ArrayList<WorkOrderDetailBean.FileDto> selectedPaths = new ArrayList<>();
        if (mBinding.multiPickResultViewHandling.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultViewHandling.getPhotos()) {
                if (photo != null && photo.getFilePath() != null && !photo.getFilePath().startsWith("http")) {
                    selectedPaths.add(photo);
                }
            }
        }

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(true)  // 允许拍照
                .setSelectedImages(selectedPaths)  // 设置已选中的图片（SelectionCreator 会处理 null 情况）
                .captureStrategy(
                        new com.nsgf.library.matisse.internal.entity.CaptureStrategy(true, "com.nsgf.daye.fileprovider", "test"))
                .maxSelectable(9)  // 最大选择9张
                .theme(R.style.Matisse_Dracula)  // 暗色主题
                .originalEnable(true)  // 显示原图选项
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(REQUEST_CODE_IMAGE_HANDLING);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (PhotoPicker.REQUEST_CODE == requestCode) {
                // 处理图片选择结果
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();

                // 获取新选择的图片路径
                for (String path : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(path);
                    photos.add(dto);
                }

                // 将选择的图片传递给MultiPickResultView
                data.putExtra(KEY_SELECTED_PHOTOS, photos);
                mBinding.multiPickResultView.onActivityResult(requestCode, resultCode, data);
            } else if (REQUEST_CODE_IMAGE_HANDLING == requestCode) {
                // 处理处理情况图片选择结果
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();

                // 获取新选择的图片路径
                for (String path : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(path);
                    photos.add(dto);
                }

                // 将选择的图片传递给MultiPickResultView，使用index=1来区分
                data.putExtra(KEY_SELECTED_PHOTOS, photos);
                data.putExtra(com.nsgf.library.photopicker.PhotoPicker.EXTRA_VIEW_ID, 1);
                mBinding.multiPickResultViewHandling.onActivityResult(requestCode, resultCode, data);
            } else if (REQUEST_CODE_VIDEO == requestCode) {
                // 处理视频选择结果
                List<String> videoPaths = Matisse.obtainPathResult(data);
                if (videoPaths != null && !videoPaths.isEmpty()) {
                    selectedVideos.clear();
                    for (String path : videoPaths) {
                        WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                        dto.setFilePath(path);
                        selectedVideos.add(dto);
                    }
                    // 更新视频显示
                    updateVideoDisplay();
                }
            } else if (REQUEST_CODE_VIDEO_HANDLING == requestCode) {
                // 处理处理情况视频选择结果（支持多个）
                List<String> videoPaths = Matisse.obtainPathResult(data);
                if (videoPaths != null && !videoPaths.isEmpty()) {
                    for (String path : videoPaths) {
                        WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                        dto.setFilePath(path);
                        selectedVideosHandling.add(dto);
                    }
                    // 更新处理情况视频显示
                    updateVideoDisplayHandling();
                }
            }
        }
    }

    /**
     * 更新天气UI
     */
    private void updateWeatherUI() {

        mAccountRequester.getWeatherDetailResult().observe(this, new Observer<DataResult<WeatherBean>>() {
            @Override
            public void onChanged(DataResult<WeatherBean> dataResult) {

                if (dataResult.getResponseStatus().isSuccess()) {
                    if (200 == dataResult.getResult().getCode()) {
                        states.weatherList.set(dataResult.getResult().getData());
                    } else {

                        if (401 == dataResult.getResult().getCode()) {
                            UserInfo.getInstance().clearUserInfo();
                            finish();
                        }
                        ToastUtils.showLongToast(dataResult.getResult().getMsg());
                    }
                } else {
                    ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
                }
            }
        });
    }

    /**
     * 更新检查结果UI
     */
    private void updateCheckResultUI() {
        if (checkResult == 0) {
            states.checkResult.set("正常");
        } else {
            states.checkResult.set("异常");
        }
        // 更新异常情况部分的显示状态
        updateAbnormalSituationVisibility();
    }
    
    /**
     * 更新异常情况部分的显示/隐藏
     */
    private void updateAbnormalSituationVisibility() {
        states.showAbnormalSituation.set(checkResult == 1);
    }

    /**
     * 保存审核记录
     */
    private void saveReview() {
        // 验证必填字段
        if (states.handler.get() == null || states.handler.get().isEmpty()) {
            showToast("请输入处理人");
            return;
        }
        
        if (states.handlingMeasures.get() == null || states.handlingMeasures.get().isEmpty()) {
            showToast("请输入处理措施");
            return;
        }
        
        // 构建JSON请求体
        JsonObject jsonObject = new JsonObject();
        
        // 处理情况信息
        jsonObject.addProperty("handler", states.handler.get() != null ? states.handler.get() : "");
        jsonObject.addProperty("handlingTime", states.handlingTime.get() != null ? states.handlingTime.get() : "");
        jsonObject.addProperty("handlingMeasures", states.handlingMeasures.get() != null ? states.handlingMeasures.get() : "");
        
        // 处理情况图片列表
        JsonArray handlingPhotos = new JsonArray();
        if (mBinding.multiPickResultViewHandling.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultViewHandling.getPhotos()) {
                if (photo != null && photo.getFilePath() != null) {
                    JsonObject photoObj = new JsonObject();
                    photoObj.addProperty("fileName", photo.getFileName() != null ? photo.getFileName() : "");
                    photoObj.addProperty("filePath", photo.getFilePath());
                    photoObj.addProperty("fileSize", photo.getFileSize());
                    handlingPhotos.add(photoObj);
                }
            }
        }
        jsonObject.add("handlingPhotos", handlingPhotos);
        
        // 处理情况视频列表
        JsonArray handlingVideos = new JsonArray();
        if (selectedVideosHandling != null && !selectedVideosHandling.isEmpty()) {
            for (WorkOrderDetailBean.FileDto video : selectedVideosHandling) {
                if (video != null && video.getFilePath() != null) {
                    JsonObject videoObj = new JsonObject();
                    videoObj.addProperty("fileName", video.getFileName() != null ? video.getFileName() : "");
                    videoObj.addProperty("filePath", video.getFilePath());
                    videoObj.addProperty("fileSize", video.getFileSize());
                    handlingVideos.add(videoObj);
                }
            }
        }
        jsonObject.add("handlingVideos", handlingVideos);
        
        // TODO: 调用保存接口
        // 创建RequestBody并调用API
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
        
        // 暂时打印日志，实际需要调用保存接口
        android.util.Log.d("PatrolReviewActivity", "保存数据: " + jsonObject.toString());
        showToast("保存成功");
        
        // 如果需要调用API，可以在这里调用
        // mAccountRequester.savePatrolReview(requestBody);
    }

    /**
     * 提交审核记录
     */
    private void submitReview() {
        // 验证必填字段
        if (states.handler.get() == null || states.handler.get().isEmpty()) {
            showToast("请输入处理人");
            return;
        }
        
        if (states.handlingMeasures.get() == null || states.handlingMeasures.get().isEmpty()) {
            showToast("请输入处理措施");
            return;
        }

        // TODO: 实现提交逻辑
        // 1. 构建JSON请求体（包含处理情况）
        // 2. 调用提交接口

        showToast("提交功能待实现");
    }

    /**
     * 点击事件代理
     */
    public class ClickProxy {
        public void onBackClick() {
            finish();
        }

        public void onWeatherClick(int index) {
            selectedWeatherIndex = index;
            updateWeatherUI();
        }

        public void onImageUploadClick() {
            // 检查权限并打开图片选择器
            openImagePicker();
        }
        
        public void onImageUploadHandlingClick() {
            // 打开处理情况图片选择器
            openImagePickerHandling();
        }

        public void onVideoUploadClick() {
            // 打开视频选择器
            openVideoPicker();
        }
        
        public void onVideoUploadHandlingClick() {
            // 打开处理情况视频选择器（支持多个）
            openVideoPickerHandling();
        }

        public void onSaveClick() {
            saveReview();
        }

        public void onSubmitClick() {
            submitReview();
        }
    }

    /**
     * States
     */
    public static class PatrolReviewStates extends StateHolder {
        public final State<String> titleBar = new State<>("审核巡查");

        // 巡查信息
        public final State<String> patrolObject = new State<>(""); // 巡查对象
        public final State<String> patrolPerson = new State<>(""); // 巡查人员
        public final State<String> patrolTime = new State<>(""); // 巡查时间
        public final State<String> waterLevel = new State<>(""); // 内湖水位
        public final State<String> patrolDuration = new State<>("0min"); // 巡查时长
        public final State<String> patrolDistance = new State<>("0m"); // 巡查距离

        // 巡查结果
        public final State<String> checkResult = new State<>("正常"); // 检查结果
        public final State<List<WeatherBean.DataBean>> weatherList = new State<List<WeatherBean.DataBean>>(null);
        
        // 异常情况
        public final State<Boolean> showAbnormalSituation = new State<>(false); // 是否显示异常情况部分
        public final State<String> situationRecord = new State<>(""); // 情况记录
        public final State<Boolean> hasVideo = new State<>(false); // 是否有视频
        public final State<StructureComponentAdapter> structureComponentAdapter = new State<>(null); // 结构组件适配器
        
        // 处理情况
        public final State<String> handler = new State<>(""); // 处理人
        public final State<String> handlingTime = new State<>(""); // 处理时间
        public final State<String> handlingMeasures = new State<>(""); // 处理措施
        public final State<Boolean> hasVideoHandling = new State<>(false); // 处理情况是否有视频
    }
}

